Page({
    data: {
      startDate: '', // 开始日期
      endDate: '',   // 结束日期
      selectedDate: '',
      showCalendar: false,
      isFormComplete: false,  // 添加表单完整性状态
  
      timeSlots: [
        '8:00-9:40',
        '9:45-11:55',
        '14:00-15:40',
        '16:00-17:25'
      ],
      selectedTimeSlot: -1, // 初始状态设为-1，表示未选择
  
      buildings: [], // 教学楼列表
      selectedBuilding: '',
      selectedBuildingText: '',
  
      rooms: [], // 教室列表
      selectedRoom: '',
      selectedRoomText: '',
    },
  
    onLoad(options) {
      const today = new Date();
      const startDate = today.toISOString().split('T')[0];
      // 设置结束日期为3天后
      const endDate = new Date(today.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  
      this.setData({
        startDate,
        endDate,
        showCalendar: false,
        selectedDate: startDate // 默认选中今天
      });

      // 显示预约提醒
      this.showBookingNotice();

      // 获取教学楼列表
      this.getBuildings();

      // 处理传入的参数
      if (options.buildingId && options.roomId) {
        // 延迟执行，等待教学楼列表加载完成
        setTimeout(() => {
          // 设置选中的教学楼
          const buildingIndex = this.data.buildings.findIndex(b => b.value === parseInt(options.buildingId));
          if (buildingIndex !== -1) {
            const selectedBuilding = this.data.buildings[buildingIndex];
            this.setData({
              selectedBuilding: selectedBuilding.value,
              selectedBuildingText: selectedBuilding.text
            });
            // 获取该教学楼下的教室列表
            this.getRooms(selectedBuilding.value, () => {
              // 设置选中的教室
              const roomIndex = this.data.rooms.findIndex(r => r.value === parseInt(options.roomId));
              if (roomIndex !== -1) {
                const selectedRoom = this.data.rooms[roomIndex];
                this.setData({
                  selectedRoom: selectedRoom.value,
                  selectedRoomText: selectedRoom.text
                });
              }
            });
          }
        }, 500);
      }
    },

    // 显示预约提醒
    showBookingNotice() {
      wx.showModal({
        title: '预约须知',
        content: '1. 预约完成后，务必按时进入教室，并且扫码教室门口的二维码核销。\n2. 务必准时到达，超过三次占座不去则拉入黑名单。\n3. 同一日期同一时间段内不能预约多个教室。\n4. 同一时间预约人数不能超过教室最大负载量。',
        confirmText: '我知道了',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            // 用户点击确定，继续预约流程
          }
        }
      });
    },

    // 获取教学楼列表
    getBuildings() {
      const app = getApp();
      wx.request({
        url: `${app.globalData.baseUrl}/admin/buildings`,
        method: 'GET',
        data: {
          page: 1,
          pageSize: 1000
        },
        success: (res) => {
          if (res.data.code === 200) {
            const buildings = res.data.data.list.map(building => ({
              value: building.id,
              text: building.name
            }));
            this.setData({ buildings });
          } else {
            wx.showToast({
              title: '获取教学楼列表失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    },

    // 获取教室列表
    getRooms(buildingId, callback) {
      const app = getApp();
      
      wx.request({
        url: `${app.globalData.baseUrl}/admin/rooms`,
        method: 'GET',
        data: {
          buildingId: buildingId,
          page: 1,
          pageSize: 100
        },
        success: (res) => {
          if (res.data.code === 200) {
            const rooms = res.data.data.list.map(room => ({
              value: room.id,
              text: room.name
            }));
            this.setData({ rooms }, () => {
              if (callback) callback();
            });
          } else {
            wx.showToast({
              title: '获取教室列表失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    },

    showCalendarPopup() {
      this.setData({ showCalendar: true });
    },

    onCloseCalendar() {
      this.setData({ showCalendar: false });
    },

    // 检查表单完整性
    checkFormComplete() {
      const isComplete = this.data.selectedDate &&
                        this.data.selectedTimeSlot !== -1 &&
                        this.data.selectedBuilding &&
                        this.data.selectedRoom;
      
      this.setData({
        isFormComplete: isComplete
      });
    },

    onConfirmDate(e) {
      const selectedDate = new Date(e.detail);
      const year = selectedDate.getFullYear();
      const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
      const day = String(selectedDate.getDate()).padStart(2, '0');
      
      this.setData({
        selectedDate: `${year}-${month}-${day}`,
        showCalendar: false
      });
      this.checkFormComplete();
    },
  
    selectTimeSlot(e) {
      const index = parseInt(e.currentTarget.dataset.index);
      if (this.data.selectedTimeSlot === index) {
        // 如果点击的是已选中的时间段，则取消选择
        this.setData({
          selectedTimeSlot: -1
        });
      } else {
        // 选择新的时间段
        this.setData({
          selectedTimeSlot: index
        });
      }
      this.checkFormComplete();
    },
  
    buildingChange(e) {
      const index = e.detail.value;
      const selected = this.data.buildings[index];
      this.setData({
        selectedBuilding: selected.value,
        selectedBuildingText: selected.text,
        selectedRoom: '',
        selectedRoomText: '',
        rooms: [] // 清空教室列表
      });
      // 获取该教学楼下的教室列表
      this.getRooms(selected.value);
      this.checkFormComplete();
    },
  
    roomChange(e) {
      const index = e.detail.value;
      const selected = this.data.rooms[index];
      this.setData({
        selectedRoom: selected.value,
        selectedRoomText: selected.text
      });
      this.checkFormComplete();
    },

    submitForm() {
      if (!this.data.isFormComplete) {
        wx.showToast({
          title: '请完善预约信息',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 构建预约数据
      const bookingData = {
        date: this.data.selectedDate,
        timeSlot: this.data.timeSlots[this.data.selectedTimeSlot],
        buildingId: this.data.selectedBuilding,
        roomId: this.data.selectedRoom,
        buildingName: this.data.selectedBuildingText,
        roomName: this.data.selectedRoomText
      };

      // 打印预约信息
      console.log('预约信息：', bookingData);
      wx.showModal({
        title: '预约信息',
        content: `日期：${bookingData.date}\n时间段：${bookingData.timeSlot}\n教学楼：${bookingData.buildingName}\n教室：${bookingData.roomName}`,
        showCancel: true,
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            // 用户点击确定，发送预约请求
            this.submitBooking(bookingData);
          }
        }
      });
    },

    // 提交预约请求
    submitBooking(bookingData) {
      const app = getApp();
      const userId = wx.getStorageSync('userInfo').id; // 获取用户ID
      
      if (!userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      wx.request({
        url: `${app.globalData.baseUrl}/admin/booking`,
        method: 'POST',
        data: {
          userId: userId,           // 添加用户ID
          date: bookingData.date,
          timeSlot: bookingData.timeSlot,
          buildingId: bookingData.buildingId,
          roomId: bookingData.roomId
        },
        success: (res) => {
            console.log(res);
          if (res.data.code==200) {
            wx.showToast({
              title: '预约成功',
              icon: 'success',
              duration: 2000
            });

            // 2秒后跳转到预约记录页面
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/orderrecord/orderrecord'
              });
            }, 2000);
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },

    // 日期选择改变
    onDateChange(e) {
      this.setData({
        selectedDate: e.detail.value
      });
      this.checkFormComplete();
    },
    goToHistory(){
        wx.switchTab({
            url: '/pages/orderrecord/orderrecord',
        })
    }
});